'use strict';

const axios = require('axios');
const dataConst = require('../constant/data-const');
const sdkConst = require('../constant/sdk-const');
const WXBizDataCrypt = require('../utility/WXBizDataCrypt');

const Service = require('egg').Service;

class WechatService extends Service {
    async geoCoder(longitude, latitude) {
        const resp = await axios.get('https://apis.map.qq.com/ws/geocoder/v1', {
            params: {
                key: sdkConst.WinXin.mapSubKey,
                location: `${latitude},${longitude}`
            }
        }).then(resp => resp.data);

        if (resp.status === 0) {
            const { result } = resp;
            const { ad_info } = result;
            return {
                success: true,
                data: ad_info
            };
        } else {
            return {
                success: false,
                data: resp.message
            };
        }
    }

    async getWeiXinDecryptData(sessionKey, encryptedData, iv) {
        const dataCrypt = new WXBizDataCrypt(sdkConst.WinXin.appid, sessionKey);
        return dataCrypt.decryptData(encryptedData, iv);
    }

    async getWeiXinUserSessionSrv(code) {
        return await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
            params: {
                appid: sdkConst.WinXin.appid,
                secret: sdkConst.WinXin.secret,
                grant_type: sdkConst.WinXin.authorizationCode,
                js_code: code
            }
        }).then(resp => resp.data);
    }

    async getAccessTokenSrv() {
        const { app } = this;

        const accessToken = await app.redis.get(dataConst.redisKeys.WX_ACCESS_TOKEN);
        if (accessToken) {
            return accessToken;
        } else {
            const { access_token, expires_in } = await axios.get('https://api.weixin.qq.com/cgi-bin/token', {
                params: {
                    grant_type: sdkConst.WinXin.clientCredential,
                    appid: sdkConst.WinXin.appid,
                    secret: sdkConst.WinXin.secret
                }
            }).then(resp => resp.data);

            await app.redis.set(dataConst.redisKeys.WX_ACCESS_TOKEN, access_token);
            await app.redis.expire(dataConst.redisKeys.WX_ACCESS_TOKEN, expires_in - 10);
            return access_token;
        }
    }
}

module.exports = WechatService;
